/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var sortList = function (head) {
  //如果head为空 或 head.next为空，返回head
  if (!head || !head.next) return head

  //前、慢、快指针寻找链表的中点
  let prev = null
  let slow = head
  let fast = head
  while (fast && fast.next) {
    prev = slow
    slow = slow.next
    fast = fast.next.next
  }
  //从中点切断链表为左、右两部分
  prev.next = null
  //继续递归切分链表的左、右两部分
  let left = sortList(head)
  let right = sortList(slow)

  //调用归并函数，将左、右两部分归并排列（升序）
  return mergeList(left, right)
};

//定义一个归并函数
function mergeList(left, right) {
  //链表头节点的前一个节点
  let dummy = new ListNode(0)
  let curr = dummy
  //归并排序两个左、右两部分（升序）
  while (left && right) {
    if (left.val < right.val) {
      curr.next = left
      left = left.next
    } else {
      curr.next = right
      right = right.next
    }
    curr = curr.next
  }
  curr.next = left || right
  //返回链表头节点
  return dummy.next
}